import logging
import sys
from pathlib import Path
from logging.handlers import RotatingFileHandler
import os
import time
import traceback

class Logger:
    _instance = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialize_logger()
        return cls._instance
    
    def _initialize_logger(self):
        """初始化日志配置"""
        try:
            # 创建logs目录
            log_dir = Path("logs")
            log_dir.mkdir(exist_ok=True)
            
            # 确保目录可写
            os.chmod(log_dir, 0o777)
            
            # 生成日志文件名（包含日期）
            current_date = time.strftime("%Y%m%d")
            log_file = log_dir / f"miaoshen_{current_date}.log"
            
            # 如果日志文件存在，确保可写
            if log_file.exists():
                os.chmod(log_file, 0o666)
            
            # 创建logger
            self.logger = logging.getLogger('MiaoShenAI')
            self.logger.setLevel(logging.DEBUG)
            
            # 简化的日志格式
            formatter = logging.Formatter(
                '[%(asctime)s] [%(levelname)s] [%(filename)s:%(lineno)d] %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'
            )
            
            # 文件处理器（按大小轮转）
            file_handler = RotatingFileHandler(
                log_file,
                maxBytes=10*1024*1024,  # 10MB
                backupCount=5,
                encoding='utf-8',
                errors='replace'  # 添加这个参数处理编码错误
            )
            file_handler.setLevel(logging.DEBUG)
            file_handler.setFormatter(formatter)
            
            # 控制台处理器
            console_handler = logging.StreamHandler(sys.stdout)
            console_handler.setLevel(logging.INFO)
            console_handler.setFormatter(formatter)
            
            # 添加处理器
            self.logger.addHandler(file_handler)
            self.logger.addHandler(console_handler)
            
        except Exception as e:
            print(f"初始化日志系统失败: {str(e)}")
            # 如果无法写入文件，使用标准输出
            handler = logging.StreamHandler(sys.stdout)
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)
    
    @classmethod
    def get_logger(cls):
        """获取日志实例"""
        if cls._instance is None:
            cls()
        return cls._instance.logger

def log_function_call(func):
    """函数调用日志装饰器"""
    def wrapper(*args, **kwargs):
        logger = Logger.get_logger()
        try:
            logger.debug(
                f"开始执行函数: {func.__name__}\n"
                f"参数: args={args}, kwargs={kwargs}"
            )
            result = func(*args, **kwargs)
            logger.debug(
                f"函数执行完成: {func.__name__}\n"
                f"返回值: {result}"
            )
            return result
        except Exception as e:
            logger.error(
                f"函数执行出错: {func.__name__}\n"
                f"错误信息: {str(e)}\n"
                f"堆栈跟踪:\n{traceback.format_exc()}"
            )
            raise
    return wrapper 